extends Node2D

var pos=Vector2i(2,-2)
var targ=Vector2(0,0)
@onready var layer_1: TileMapLayer = $"../tile_map/layer1"
@onready var layer_0: TileMapLayer = $"../tile_map/layer0"
@onready var timer: Timer = $timer
@onready var bgm: AudioStreamPlayer2D = $bgm

var inner_world
var path
var offset=Vector2i(1,0)
var moveable=true
var unstable=false

func _ready() -> void:
	inner_world=get_tree().get_first_node_in_group("inner_world")

func _move():
	path=layer_1.get_used_cells()
	if layer_1.get_cell_source_id(pos+offset)==4:
		inner_world._reset()
	if Input.is_action_just_pressed("down"):
		_move_check(Vector2i(0,1))
	elif Input.is_action_just_pressed("up"):
		_move_check(Vector2i(0,-1))
	elif Input.is_action_just_pressed("left"):
		_move_check(Vector2i(-1,0))
	elif Input.is_action_just_pressed("right"):
		_move_check(Vector2i(1,0))
	elif Input.is_action_just_pressed("reset"):
		inner_world._reset()
	targ=layer_1.map_to_local(pos)
	self.global_position=lerp(self.global_position,targ,0.3)

func _stable_check(dir):
	if unstable:
		layer_1.erase_cell(pos+offset-dir)
		layer_0.set_cell(pos+offset-dir,0,Vector2i(0,7))
		unstable=false
	if not unstable:
		if layer_1.get_cell_source_id(pos+offset)==2:
			unstable=true

func _move_check(dir:Vector2i):
	if not moveable:
		return
	if pos+offset+dir in path:
		pos+=dir
		_stable_check(dir)
		for shard in get_tree().get_nodes_in_group("shards"):
			shard._move()
		timer.start()
		moveable=false

func _physics_process(delta: float) -> void:
	if not bgm.playing:
		bgm.play()
	_move()
	if not global.flag_list["hint2"]:
		if pos==Vector2i(28,25)-offset:
			global.flag_list["hint2"]=1
			global.cur_line="hint2"
			global.cur_index=0
			get_tree().get_first_node_in_group("game_scene")._chat_in()
	if not global.flag_list["hint3"]:
		if pos==Vector2i(19,30)-offset:
			global.flag_list["hint3"]=1
			global.cur_line="hint3"
			global.cur_index=0
			get_tree().get_first_node_in_group("game_scene")._chat_in()
	if not global.flag_list["hint4"]:
		if pos==Vector2i(-8,4)-offset:
			global.flag_list["hint4"]=1
			global.cur_line="hint4"
			global.cur_index=0
			get_tree().get_first_node_in_group("game_scene")._chat_in()
		
func _on_timer_timeout() -> void:
	moveable=true
